package com.wendy.interceptor;

import com.wendy.mapper.AuthorityMapper;
import com.wendy.mapper.RoleMapper;
import com.wendy.model.Authority;
import com.wendy.model.Role;
import com.wendy.utils.Constants;
import com.wendy.utils.RequestUriHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author zhuwending
 */
@Component
@Slf4j
public class Interceptor implements HandlerInterceptor {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AuthorityMapper authorityMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        /*if (!isNeedPermissions(request)) {
            throw new AccessDeniedException("restful no permissions");
        }*/
        return true;
    }

    private boolean isNeedPermissions(HttpServletRequest request) {
        boolean flag = true;
        Principal principal = request.getUserPrincipal();
        if (principal == null) {
            flag = false;
        }
        if (principal instanceof UsernamePasswordAuthenticationToken) {
            Collection<? extends GrantedAuthority> collection = ((UsernamePasswordAuthenticationToken) principal).getAuthorities();
            if (collection != null && collection.size() > 0) {
                String uri = request.getRequestURI();
                if (uri.contains(Constants.QUESTION_MARK)) {
                    uri = uri.substring(0, uri.indexOf(Constants.QUESTION_MARK));
                }
                if (!RequestUriHandler.needPermissions(uri)) {
                    List<String> list = new ArrayList<>(16);
                    if (uri.startsWith(Constants.MENU_PATH)) {
                        List<Role> roles = roleMapper.selectRoleByMenuPath(uri);
                        if (roles != null && roles.size() > 0) {
                            roles.forEach(role -> list.add(role.getCode()));
                        }
                    } else {
                        List<Authority> authorities = authorityMapper.selectAuthorityByResourceUri(uri);
                        if (authorities != null && authorities.size() > 0) {
                            authorities.forEach(authority -> list.add(authority.getPermissions()));
                        }
                    }
                    if (list.size() == 0) {
                        flag = false;
                    } else {
                        for (GrantedAuthority authority : collection) {
                            if (list.contains(authority.getAuthority())) {
                                return true;
                            }
                        }
                    }
                }
            } else {
                flag = false;
            }
        } else {
            flag = false;
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
